package com.roc.web.dwr;
/**
 * @author zbl
 * @DATE  2014-08-10
 * dwr 加载mcc
 * */
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.springframework.beans.factory.annotation.Autowired;

import com.roc.bean.orgMainBean;
import com.roc.dao.DaoException;
import com.roc.dao.ISQLBaseDao;
import com.roc.page.BaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.ProfitModule;
import com.roc.pojo.ProfitPercentModule;
import com.roc.pojo.ProfitRuleModule;
import com.roc.pojo.TblArea;
import com.roc.pojo.TblDictionaryLayerItem;
import com.roc.service.IAgentService;
import com.roc.service.IMerchantServices;
import com.roc.service.IModelService;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.util.constant.TerminalName;
@RemoteProxy
public class MccQuery extends BaseAction{
	static Logger logger = LogManager.getLogger(MccQuery.class);
		
	@Resource(name = "sqlBaseDao")
	private ISQLBaseDao sqlBaseDao;
	
	
	@Autowired
	private IMerchantServices merchantServices;

	@Autowired
	ITerminalService terminalService;
	@Autowired
	IModelService modelService;
	@Autowired
	IAgentService  agentService;
	@Autowired
	IPowerInfoService powerInfoService;
	@Autowired
	IorgService orgService;
	
	//查询 mcctype
	@RemoteMethod
	public List<Map<String, Object>> loadMccType(){
		
		logger.debug("one ");
		List<Map<String, Object>> queryResult = null;

		try {
			
			String sql = "select mcc_type_code as code, mcc_type_name as name from t_mcc_type ";
			queryResult = sqlBaseDao.querySqlToMap(sql);
		} catch (DaoException e) {
			logger.debug("加载mcc_type信息失败",e);
		}
		return queryResult;
	}
	
	//根据mcctype  load  mcccode
	@RemoteMethod
	public List<Map<String, Object>> loadMccCode(String super_id) {
		logger.debug("two " + super_id);
		List<Map<String, Object>> queryResult = null;

		try {
			
			String sql = "SELECT mcc_code as code,'['||mcc_code||']'||mcc_product_name  as name FROM t_mcc_code  WHERE mcc_type='"+super_id+"' ORDER BY  mcc_code  ";
			queryResult = sqlBaseDao.querySqlToMap(sql);
		} catch (NumberFormatException nfe) {
			logger.debug("代码非法:"+super_id,nfe);
		} catch (DaoException e) {
			logger.debug("加载mcc_code信息失败",e);
		}
		return queryResult;
	}
	
	
	//根据机构号查询机构管理员(O单管理员)
	@RemoteMethod
	public List<Map<String, Object>> loadOCode(String orgCode) throws ServiceException {
		
		List<Map<String, Object>> queryResult = null;

		String sql="";
		try {
			Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			//O 单
			if(Constance.OPERATORS_FLAG_OEM.equals(logingMerchant.getFlag())){
				if(logingMerchant.getRoleType().equals(Role.AGENT.getCode())){
					sql=" SELECT id as code,real_name as name FROM t_operators t start WITH id ="+logingMerchant.getId()+" and t.role_type = '"+Role.AGENT.getCode()+"' connect BY prior t.id = t.supri_id order by t.real_name DESC ";
				}else{
					sql=" SELECT id as code,real_name as name FROM t_operators t where  t.role_type in( '"+Role.AGENT.getCode()+"','"+Role.O_MANAGER.getCode()+"' ) and t.org_code = '"+orgCode+"'  order by t.real_name DESC ";
					
				}
			}else{
				sql=" SELECT id as code,real_name as name FROM t_operators t where  t.role_type in( '"+Role.AGENT.getCode()+"','"+Role.O_MANAGER.getCode()+"' ) and t.org_code = '"+orgCode+"'  order by t.real_name DESC ";
			}
			queryResult = sqlBaseDao.querySqlToMap(sql);
		} catch (NumberFormatException nfe) {
			logger.debug("代码非法:"+orgCode,nfe);
		} catch (DaoException e) {
			logger.debug("加载代理商",e);
		}
		return queryResult;
	}

	//根据机构号查询机构管理员(O单管理员)
		@RemoteMethod
		public List<Map<String, Object>> loadOEMAdmin(String orgCode) throws ServiceException {
			
			List<Map<String, Object>> queryResult = null;

			String sql="";
			try {
				
				sql=" SELECT id as code,real_name as name FROM t_operators t where  t.role_type='"+Role.O_MANAGER.getCode()+"'  and t.org_code = '"+orgCode+"'  order by t.real_name DESC ";
				
				queryResult = sqlBaseDao.querySqlToMap(sql);
			} catch (NumberFormatException nfe) {
				logger.debug("代码非法:"+orgCode,nfe);
			} catch (DaoException e) {
				logger.debug("加载代理商",e);
			}
			return queryResult;
		}
		
		
		
		//通过ID加载对应的机器代码
		@RemoteMethod
		public List<Map<String, Object>> loadBrandNameById(String brandId) throws ServiceException {
			
			List<Map<String, Object>> queryResult = new ArrayList<Map<String,Object>>();
			
			try {
				
				Map<String,String> brandNameMap = TerminalName.getAllEnumMap();
				Set<String> keyset = brandNameMap.keySet();  
				    for(String key : keyset){  
				          if(key.startsWith(brandId)){
				        	  HashMap<String,Object> aMap = new HashMap<String, Object>();
				        	  aMap.put("CODE", brandNameMap.get(key));
				        	  aMap.put("NAME", brandNameMap.get(key));
				        	  queryResult.add(aMap);
				          }
				    }  

			} catch (NumberFormatException nfe) {
				logger.debug("品牌名称id异常:"+brandId,nfe);
			} catch (Exception e) {
				logger.debug("加载对应的机器代码异常",e);
			}
			return queryResult;
		}
		
		
		//通过Code加载对应的机器代码
		@RemoteMethod
		public List<Map<String, Object>> loadBrandNameByCode(String brandId) throws ServiceException {
			
			List<Map<String, Object>> queryResult = new ArrayList<Map<String,Object>>();
			
			try {
				TblDictionaryLayerItem itemModel = new TblDictionaryLayerItem();
				itemModel.getId().setDicPcode(brandId);
				queryResult = terminalService.selModelItemByType(itemModel);
				
			} catch (NumberFormatException nfe) {
				logger.debug("品牌名称id异常:"+brandId,nfe);
			} catch (Exception e) {
				logger.debug("加载对应的机器代码异常",e);
			}
			return queryResult;
		}
		
		
		//通过Code加载对应的云商宝机器代码
		@RemoteMethod
		public List<Map<String, Object>> loadYsbBrandNameByCode(String brandId) throws ServiceException {
			
			List<Map<String, Object>> queryResult = new ArrayList<Map<String,Object>>();
			
			try {
				queryResult = ConfigProperties.getYsbModelProperties(brandId);
				
			} catch (NumberFormatException nfe) {
				logger.debug("云商宝品牌名称id异常:"+brandId,nfe);
			} catch (Exception e) {
				logger.debug("加载对应的云商宝机器代码异常",e);
			}
			return queryResult;
		}
		
		@RemoteMethod
		public List<Map<String, Object>> loadSonOper(String id) throws ServiceException {
			
			List<Map<String, Object>> queryResult = null;

			String sql="";
			try {
				sql="SELECT ID AS CODE, REAL_NAME AS NAME FROM T_OPERATORS T WHERE t.role_type='03' and SUPRI_ID="+id.trim();
				queryResult = sqlBaseDao.querySqlToMap(sql);
			} catch (NumberFormatException nfe) {
				logger.debug("代码非法:"+id,nfe);
			} catch (DaoException e) {
				logger.debug("加载["+id+"]下级代理商出错",e);
			}
			return queryResult;
		}	

		@RemoteMethod
		public List<Map<String, Object>> loadOneAgent(String id) throws ServiceException {
			List<Map<String, Object>> queryResult = new ArrayList<Map<String,Object>>();

			try {
				List<Operators> oneAgengList = merchantServices.queryLowOneAgent(id);
				for (Operators bean : oneAgengList) {

		        	  HashMap<String,Object> aMap = new HashMap<String, Object>();
		        	  aMap.put("CODE", bean.getId());
		        	  aMap.put("NAME", bean.getRealName());
		        	  queryResult.add(aMap);
				}
			} catch (NumberFormatException nfe) {
				logger.debug("代码非法:"+id,nfe);
			} catch (ServiceException e) {
				logger.debug("加载["+id+"]直属代理商出错",e);
			}
			return queryResult;
		}	
		

		@RemoteMethod
		public List<List<Map<String, Object>>> queryDefProfitModelInfo() throws ServiceException {
			List<List<Map<String, Object>>> queryResult = new ArrayList<List<Map<String, Object>>>();
			Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

			try {
				// 查询当前默认的模板信息
				ProfitModule bean = modelService.queryDefProfitModuleByAgentId( logingOperators.getId());
				if( null != bean ){
					String modelId = String.valueOf(bean.getId());
					
					List<ProfitRuleModule> profitRuleModuleList = modelService.queryProfitRuleModule(logingOperators.getId(), modelId);
					List<Map<String, Object>> ruleMap = getRuleInfoList(profitRuleModuleList);
					queryResult.add(ruleMap);
					
					List<ProfitPercentModule> profitPerModuleList = modelService.queryProfitPercentModule(logingOperators.getId(), modelId);
					List<Map<String, Object>> proList = getPreInfoList(profitPerModuleList);
					queryResult.add(proList);
				}
				
			}  catch (ServiceException e) {
				logger.debug("加载[" + logingOperators.getAccountNo() + "]默认分润模板出错",e);
			}
			return queryResult;
		}	

		public List<Map<String, Object>> getPreInfoList(List<ProfitPercentModule> perList){
			List<Map<String, Object>> perListNew  = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = new HashMap<String, Object>();
			
			for (ProfitPercentModule per : perList) {
				String percentStr = per.getPercent();
				Double perDouble = Double.parseDouble(percentStr) * 100;
				// double 转 int 类型,便于页面显示
				BigDecimal b = new BigDecimal(perDouble);
				int percent = b.intValue();
				
				map = new HashMap<String, Object>();
				map.put("limitAmt", per.getLimitAmt() ); // 区间最小金额
				map.put("maxAmt", per.getMaxAmt() ); // 区间最大金额
				map.put("percent", String.valueOf( percent ) ); // 分润比例
				
				perListNew.add(map);
			}
			return perListNew;
		}
		
		
		public List<Map<String, Object>> getRuleInfoList(List<ProfitRuleModule> ruleList){
			List<Map<String, Object>> porListNew  = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = new HashMap<String, Object>();
			
			for(ProfitRuleModule pro:ruleList){
				map = new HashMap<String, Object>();
				
				map.put("mccTypeCode", pro.getMccTypeCode() ); // mcc 编码
				map.put("mccTypeName", pro.getMccTypeName() ); // mcc 名称
				map.put("profitFee", pro.getProfitFee() ); // 
				map.put("profitSettleRate", pro.getProfitSettleRate() ); // 
				map.put("merchantMinFee", pro.getMerchantMinFee() ); // 
				map.put("maxFee", pro.getMaxFee() ); // 

				porListNew.add(map);
			}
			return porListNew;
			
		}
		

		
		//通过oneOrgCod返回对应的区域属性id
		@RemoteMethod
		public String loadAreaByOneOrgCode(String oneOrgCode) throws ServiceException {
			String areaCode = "";
			try {
				if ( null != oneOrgCode && !"".equals(oneOrgCode) ){
					orgMainBean orgMainObj = orgService.queryOrgMainByOrgMain( oneOrgCode );
					areaCode = orgMainObj.getAreaId();
					
				}
				
			} catch (NumberFormatException nfe) {
				logger.debug("所属机构管理code异常:"+oneOrgCode,nfe);
			} catch (Exception e) {
				logger.debug("加载对应的区域代码异常",e);
			}
			return areaCode;
		}
		
		@RemoteMethod
		public List<Map<String, Object>> loadNewOneAgentInf(String id) throws ServiceException {
			List<Map<String, Object>> queryResult = new ArrayList<Map<String,Object>>();
			try {
				List<Operators> oneAgengList = merchantServices.queryAllOneAgent(id);
				for (Operators bean : oneAgengList) {
					HashMap<String,Object> aMap = new HashMap<String, Object>();
					aMap.put("CODE", bean.getOneagentid());
					aMap.put("NAME", bean.getRealName());
					queryResult.add(aMap);
				}
			} catch (NumberFormatException nfe) {
				logger.debug("代码非法:"+id,nfe);
			} catch (ServiceException e) {
				logger.debug("加载分公司["+id+"]下属一级代理商出错",e);
			}
			return queryResult;
		}	
}
